<template>
  <div class="pie-gadget-css"
       style="width:100;height:100%"
       :id="id">
    <Portal to="right-disable"
            style="width:100;height:100%"
            :disabled="!queryModelDefaultSetting.showSetting">
      <DashboardInterceptConsumer :gadgetId="id"
                                  shadow="never"
                                  class="aui-card--fill"
                                  @mouseenter="mouseenter(true)"
                                  @mouseleave="mouseenter(false)"
                                  style="width:100%;height: 100%;border:0">
        <el-card shadow="never"
                 v-loading="loading"
                 style="width:100%;height: 100%;border:0"
                 class="aui-card--fill">
          <div style="width:100%;height:100%;">
            <div class="cardHeader"
                 @mouseenter="mouseenter(true)"
                 @mouseleave="mouseenter(false)"
                 v-if="(widgetName && widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
              <GadgetTitle :gadgetSetting="gadgetSetting"
                           :widgetName="widgetName"></GadgetTitle>
              <div>
                <MoreMenu :slicer='slicer'
                          :fitToHeight='fitToHeight'
                          :gadgetId='id'
                          :gadgetType='gadgetInfo.com'
                          @updateQuery="query"
                          :widgetName="widgetName"
                          :businessType="gadgetInfo.businessType"
                          :id="gadgetInfo.id"
                          @showQueryModel="showQueryModel"
                          @fullScreen="fullScreen" />
              </div>
            </div>
            <div class="control-section control-section2">
              <div class=content-wrapper
                   style="width:100%;height:100%;">
                <div v-if="isHasData"
                  style="width:100%;height:100%;">
                  <div class="echarts-title" style="height:30px;line-height: 30px;font-size:16px;font-weight:700;text-align:center">{{gadgetSetting.title}}</div>
                  <div :id="selfGadgetUuid" style="width:100%;height:calc(100% - 30px);"></div>
                </div>
                <div v-else
                    class="gadget-no-newdata">
                    <div class="widgets-no-data">
                    <div :style="{'fontSize':fontSizeStr1}">{{$t('custom.component.gadget.nodata')}}</div>
                    <!-- <div class="widgets-tip"> <a :href="widgetNoDataWiki"  :style="{'fontSize':fontSizeStr2}"
                         target="black">{{$t('custom.component.gadget.nodatatip')}}</a> </div> -->
                  </div>
                </div>
              </div>
            </div>

          </div>
        </el-card>
        <Lastupdatetime v-if="currentTime"
                        :currentTime="currentTime"
                        :linkedDatasetList="linkedDatasetList"
                        :errorStatus="errorStatus"
                        @updateQuery="query()"></Lastupdatetime>
      </DashboardInterceptConsumer>

    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           :slicer='slicer' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
    <div style="position:absolute;left:9999px;">
      <component v-for="(item, index) in formatComponentList"
                 :key="index"
                 :is="item"
                 :ref="item"
                 gadgetType='notgridgadget' />
    </div>
  </div>
</template>

<script>
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import { getUUID } from '@/utils'
import * as Echarts from 'echarts'
import { isNotNullValue } from '@/utils/common'
export default ({
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime, model: () => import('@/components/gadget/query-model/query-model') },
  data: function () {
    return {
      selfGadgetUuid: getUUID(),
      repeatNumber: 0,
      chartOption: {
        title: {
          text: '',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br />{b}: {c}'
        },
        color: [
          '#5c7bd9',
          '#9fe080',
          '#ffec92',
          '#ff7070',
          '#7ed3f4',
          '#40b27d',
          '#ff915a',
          '#a969c6',
          '#fe87df'
        ],
        legend: {
          show: false,
          type: 'scroll',
          orient: 'vertical',
          right: 10,
          bottom: 30,
          formatter: '{name}',
          left: 'left'
        },
        grid: {
          // top: '10px',
          left: '10px',
          right: '10px',
          bottom: '10px',
          width: '94%',
          // height: '85%',
          containLabel: true
        },
        series: []
      },
      chartDom: null,
      currentTime: null,
      queryData: [],
      queryFields: [],
      theme: 'Material',
      dataSource: [],
      gadgetSetting: null,
      loading: false,
      chartWidth: '600px',
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'piechartgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'piechartgadget' }).gadgetSetting
          // gadgetSetting: {
          //   theme: 'Material',
          //   title: '',
          //   valueFieldsNameMeasureX: 'x',
          //   valueFieldsNameMeasureY: 'y',
          //   valueFieldsNameMeasureText: 'text',
          //   legendSettings: {
          //     visible: false
          //   },
          //   tooltip: {
          //     enable: true,
          //     format: '$' + `{point.x} : <b>$` + `{point.y}</b>`
          //   },
          //   enableAnimation: false,
          //   center: { x: '50%', y: '50%' },
          //   startAngle: '0',
          //   endAngle: '360',
          //   radius: '70%',
          //   explodeOffset: '10%',
          //   explodeIndex: 0,
          //   dataLabel: {
          //     visible: true,
          //     position: 'Inside',
          //     name: 'text',
          //     font: {
          //       fontWeight: '600'
          //     }
          //   },
          //   headerTitle: '',
          //   headerDescription: ''
          // }
        }
      },
      queryId: '',
      queryDrillthrough: {},
      widgetName: '',
      linkedDatasetList: []
    }
  },

  created () {
    this.gadgetHeight = (this.gadgetInfo.h * 20) - 45
    // this.query()
    this.subscribeMessage('runReport', () => {
      this.query(this.refreshCount > 0 ? 'auto' : false)
      this.refreshCount = this.refreshCount + 1
    })
    this.$store.state.isWidget = false
  },
  updated () {
    if (document.getElementById(`${this.selfGadgetUuid}`) && document.getElementById(`${this.selfGadgetUuid}`).offsetWidth) {
      let wW = document.getElementById(`${this.selfGadgetUuid}`).offsetWidth
      let wH = document.getElementById(`${this.selfGadgetUuid}`).offsetHeight
      this.gadgetSetting.titleFontSize = (parseInt(wW / 70) + parseInt(wH / 200))<10?'10px':(parseInt(wW / 70) + parseInt(wH / 200) + 'px')
    }
  },
  methods: {
    updateChart (originData) {
      let _self = this
      this.chartDom = document.getElementById(`${this.selfGadgetUuid}`)
      if (!this.chartDom) {
        setTimeout(() => {
          this.repeatNumber++
          this.updateChart(originData)
        }, 1000)
      } else if (!Array.isArray(originData) || (Array.isArray(originData) && originData.length === 0)) {
        Echarts.init(this.chartDom).dispose()
      } else {
        if (!this.gadgetSetting.valueFieldsNameMeasuresubX) {
          this.repeatNumber = 0
          let myChart = Echarts.init(this.chartDom, this.globalTheme) 
          // this.chartOption.title.text = this.gadgetSetting.title
          this.chartOption.title.textStyle = { fontSize: this.gadgetSetting.titleFontSize || 18 }
          this.chartOption.series = []
          let lastObj = {
            name: this.gadgetSetting.valueFieldsNameMeasureX || this.gadgetSetting.valueFieldsNameMeasureText,
            type: 'pie',
            radius: '70%',
            label: {
              formatter: '{a}<br />{b}: {c}',
              rich: {
                time: {
                  fontSize: 10,
                  color: '#999'
                }
              }
            },
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
          this.chartOption.legend.data = []
          for (let i = 0; i < originData.length; i++) {
            const groupItem = originData[i]
            let areaName = isNotNullValue(groupItem[this.gadgetSetting.valueFieldsNameMeasureX]) ? groupItem[this.gadgetSetting.valueFieldsNameMeasureX] : null
            groupItem[this.gadgetSetting.valueFieldsNameMeasureY] && this.chartOption.legend.data.push(areaName)
            lastObj.data.push({ value: groupItem[this.gadgetSetting.valueFieldsNameMeasureY], name: areaName })
          }
          this.chartOption.series.push(lastObj)

          this.chartOption.tooltip.formatter = (params) => {
            if (!this.gadgetSetting.pieName) {
              if (this.gadgetSetting.name) {
                this.gadgetSetting.pieName = this.gadgetSetting.name
              } else {
                this.gadgetSetting.pieName = ''
              }
            }

            return `${this.gadgetSetting.pieName ? this.gadgetSetting.pieName + ' <br /> ' : ''}${this.setFormatFunctionForChart(this.queryFields, params.data.name, this.gadgetSetting.valueFieldsNameMeasureX)}:
                    ${this.setFormatFunctionForChart(this.queryFields, params.value, this.gadgetSetting.valueFieldsNameMeasureY)} (${params.percent}%)`
          }
          for (let i = 0; i < this.chartOption.series.length; i++) {
            const element = this.chartOption.series[i]
            element.label.formatter = (params) => {
              return `${this.setFormatFunctionForChart(this.queryFields, params.data.name, this.gadgetSetting.valueFieldsNameMeasureX)}: ${this.setFormatFunctionForChart(_self.queryFields, params.value, _self.gadgetSetting.valueFieldsNameMeasureY)} (${params.percent}%)\n`
            }
          }
          this.chartOption.legend.formatter = (value) => {
            return `${this.setFormatFunctionForChart(this.queryFields, value, this.gadgetSetting.valueFieldsNameMeasureX)}`
          }
          this.setColors(this.chartOption)
          myChart.setOption(this.chartOption)
          myChart.on('click', params => {
            params.name = params.data.name
            this.setDrillThroughInfo(params, this.queryModelDefaultSetting.dataInfo.gadgetType)
          })
          this.$erd.listenTo(this.chartDom, element => {
          this.$nextTick(() => {
            this.resized()
          })
        })
        } else {
          this.repeatNumber = 0
          let myChart = Echarts.init(this.chartDom, this.globalTheme) 
          // this.chartOption.title.text = this.gadgetSetting.title
          this.chartOption.series = []
          var lastObj = {
            name: this.gadgetSetting.valueFieldsNameMeasuresubX || this.gadgetSetting.valueFieldsNameMeasureText,
            type: 'pie',
            radius: [0, '50%'],
            label: {
              position: 'inner',
              formatter: '{a}<br />{b}: {c}',
              rich: {
                time: {
                  fontSize: 10,
                  color: '#999'
                }
              }
            },
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
          this.chartOption.legend.data = []
          var arr = this._.uniqBy(originData, this.gadgetSetting.valueFieldsNameMeasureX)
          arr.forEach(item => {
            var rr = originData.filter(i => i[this.gadgetSetting.valueFieldsNameMeasureX] === item[this.gadgetSetting.valueFieldsNameMeasureX])
            var count = 0
            rr.forEach(ii => {
              count += Number(ii[this.gadgetSetting.valueFieldsNameMeasureY])
            })
            var obj = {
              name: item[this.gadgetSetting.valueFieldsNameMeasureX],
              value: count
            }
            this.chartOption.legend.data.push(item[this.gadgetSetting.valueFieldsNameMeasureX])
            lastObj.data.push(obj)
          })
          this.chartOption.series.push(lastObj)
          this.chartOption.tooltip.formatter = (params) => {
            if (!this.gadgetSetting.pieName) {
              if (this.gadgetSetting.name) {
                this.gadgetSetting.pieName = this.gadgetSetting.name
              } else {
                this.gadgetSetting.pieName = ''
              }
            }
            return `${this.gadgetSetting.pieName ? this.gadgetSetting.pieName + ' <br /> ' : ''}${this.setFormatFunctionForChart(this.queryFields, params.data.name, this.gadgetSetting.valueFieldsNameMeasureX)}:
                    ${this.setFormatFunctionForChart(this.queryFields, params.value, this.gadgetSetting.valueFieldsNameMeasureY)} (${params.percent}%)`
          }
          for (let i = 0; i < this.chartOption.series.length; i++) {
            const element = this.chartOption.series[i]
            element.label.formatter = (params) => {
              return `${this.setFormatFunctionForChart(this.queryFields, params.data.name, this.gadgetSetting.valueFieldsNameMeasureX)}: ${this.setFormatFunctionForChart(this.queryFields, params.value, this.gadgetSetting.valueFieldsNameMeasureY)} (${params.percent}%)\n`
            }
          }
          this.chartOption.legend.formatter = (value) => {
            return `${this.setFormatFunctionForChart(this.queryFields, value, this.gadgetSetting.valueFieldsNameMeasureX)}`
          }
          var outsideObj = {
            name: this.gadgetSetting.valueFieldsNameMeasureX || this.gadgetSetting.valueFieldsNameMeasureText,
            type: 'pie',
            radius: ['50%', '80%'],
            label: {
              formatter: '{a}<br />{b}: {c}',
              rich: {
                time: {
                  fontSize: 10,
                  color: '#999'
                }
              }
            },
            data: [],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
          originData = originData.sort(function (a, b) {
            return (a[_self.gadgetSetting.valueFieldsNameMeasureX] + '').localeCompare((b[_self.gadgetSetting.valueFieldsNameMeasureX] + ''))
          })
          for (var i = 0; i < originData.length; i++) {
            const groupItem = originData[i]
            let areaName = isNotNullValue(groupItem[this.gadgetSetting.valueFieldsNameMeasuresubX]) ? groupItem[this.gadgetSetting.valueFieldsNameMeasuresubX] : null
            outsideObj.data.push({ value: groupItem[this.gadgetSetting.valueFieldsNameMeasureY], name: areaName })
          }
          this.chartOption.series.push(outsideObj)

          this.chartOption.tooltip.formatter = (params) => {
            if (!this.gadgetSetting.pieName) {
              if (this.gadgetSetting.name) {
                this.gadgetSetting.pieName = this.gadgetSetting.name
              } else {
                this.gadgetSetting.pieName = ''
              }
            }
            return `${this.gadgetSetting.pieName ? this.gadgetSetting.pieName + ' <br /> ' : ''}${this.setFormatFunctionForChart(this.queryFields, params.data.name, this.gadgetSetting.valueFieldsNameMeasuresubX)}:
                    ${this.setFormatFunctionForChart(this.queryFields, params.value, this.gadgetSetting.valueFieldsNameMeasureY)} (${params.percent}%)`
          }
          const element = this.chartOption.series[1]
          element.label.formatter = (params) => {
            return `${this.setFormatFunctionForChart(this.queryFields, params.data.name, this.gadgetSetting.valueFieldsNameMeasuresubX)}: ${this.setFormatFunctionForChart(this.queryFields, params.value, this.gadgetSetting.valueFieldsNameMeasureY)} (${params.percent}%)\n`
          }
          this.chartOption.legend.formatter = (value) => {
            return `${this.setFormatFunctionForChart(this.queryFields, value, this.gadgetSetting.valueFieldsNameMeasuresubX)}`
          }
          this.setColors(this.chartOption)
          myChart.setOption(this.chartOption)
          myChart.on('click', params => {
            params.name = params.data.name
            this.setDrillThroughInfo(params, this.queryModelDefaultSetting.dataInfo.gadgetType, originData)
          })
          this.$erd.listenTo(this.chartDom, element => {
            this.$nextTick(() => {
              this.resized()
            })
          })
        }
      }
    },
    setColors (chartOption) {
      let color = [
        '#5c7bd9',
        '#9fe080',
        '#ffec92',
        '#ff7070',
        '#7ed3f4',
        '#40b27d',
        '#ff915a',
        '#a969c6',
        '#fe87df'
      ]
      try {
        // if (chartOption.series.some(item => item.data.length > 9)) {
        //   let arr = chartOption.series.map((item, index) => {
        //     return {
        //       index: index,
        //       length: item.data.length
        //     }
        //   })
        //   let arr1 = arr.map(i => i.length)
        //   let maxLength = Math.max.apply(null, arr1)
        //   let res = arr.find(i => i.length === maxLength)
        //   let r = 'ea7ccc'
        //   chartOption.series[res.index].data.forEach((i, index) => {
        //     if (index >= 9) {
        //       r = (parseInt(r, 16) * 11).toString(16).slice(0, 6)
        //       chartOption.color.push(`#${r}`)
        //     }
        //   })
        // }
        this.chartOption.series = chartOption.series.map(v => {
          v.data.map((v, i) => {
            let setColor = this.gadgetSetting.Thresholds && JSON.parse(this.gadgetSetting.Thresholds).find(vp => vp.value === v.name + '') ? JSON.parse(this.gadgetSetting.Thresholds).find(vp => vp.value === v.name + '').color : color[i % 9]
            v.itemStyle = { color: setColor }
            return v
          })
          return v
        })
      } catch (error) {

      }
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query()
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      setTimeout(() => {
        let myChart = Echarts.init(this.chartDom, this.globalTheme)
        myChart.resize()
      }, 0)
    },
    containerResizedEvent (i, newH, newW, newHPx, newWPx) {
      this.chartWidth = (newWPx - 10) + 'px'
    },
    query (e) {
      this.gadgetSetting = this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      if (e !== 'auto') {
        this.loading = true
      }
      var _self = this
      var obj = JSON.parse(JSON.stringify(this.slicer))
      let tempObj = this.returnReportLinkParam()
      if (tempObj['name'] && this.slicer['name'] && tempObj['name'] === this.slicer['name']) delete this.slicer['name']
      for (var key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      var param = {
        ...obj,
        code: this.code,
        gadgettype: this.wgadgettype,
        widgetName: this.wName,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      this.$interface.reports.getReportDataInfo(param).then(({ data: res }) => {
         
        try {
          _self.$parent.$parent.$parent.$parent.$parent.$parent.selectFields = res.selectFields
        } catch (error) {
        }
        _self.verifyHasData(res)
        if (res.config) {
          if(this._.get(this.dataInfo,'gadgetSetting.dynamic',false)){
              _self.gadgetSetting =this._.cloneDeep(this.dataInfo.gadgetSetting)  
          }else{
              _self._.merge(_self.gadgetSetting, res.config)
          }
        }
        if (!_self.gadgetSetting.headerDescription || _self.gadgetSetting.headerDescription === null) {
          _self.gadgetSetting.headerDescription = ''
        }
        if (res.name) {
          _self.widgetName = res.name
        } else if (this.wName) {
            _self.widgetName = this.wName
        }  else {
          _self.widgetName = _self.gadgetSetting.headerTitle
        }
        this.fxFields = res.fxFields || []
        if (res.data) {
          _self.currentTime = new Date()
          _self.updateChart(res.data)
          _self.queryData = res.data
          _self.queryFields = res.selectFields
          _self.linkedDatasetList = res.datasetSync
        }
      }).catch((error) => {
          if (this.wName) {
          this.widgetName = this.wName
        }
        Echarts.init(this.chartDom).dispose()
        this.isHasData = false
        this.currentTime = new Date()
        this.loading = false
        if (error.response && error.response.status === 504) {
          this.errorStatus = '504'
          this.gadgetMessageBus.$emit(this.pageId + 'stopautorefresh')
        }
      }).finally(() => {
        this.autoRefreshQuery(e)
        this.updateGadgetLoadingStatus(!this.loading)
      })
    }
  }
})
</script>
<style lang="scss" scoped>
.content-wrapper {
  position: relative;
  .gadget-no-newdata {
    position: absolute;
    top: 40%;
    left: 0;
    right: 0;
    margin: 0 auto;
    .widgets-no-data {
      display: flex;
      flex-direction: column;
      align-items: center;
      .widgets-tip {
        margin-top: 5px;
      }
    }
  }
}
</style>
<style scoped>
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}
</style>
<style lang="scss">
.pie-gadget-css {
  .el-card__body {
    width: 100%;
    height: 100%;
  }
  .control-section2 {
    width: 100%;
    height: calc(100% - 34px);
  }
}
</style>
